package com.topnav.mc.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.js.lib.cache.listener.AbstractMessageListener;
import com.js.lib.utils.DateUtils;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.listener.bean.CommMessage;
import com.topnav.mc.listener.bean.ECommMessageType;
import com.topnav.mc.listener.bean.GPSMsgInfo;
import com.topnav.mc.sse.DeviceAlarmQueue;
import com.topnav.mc.sse.EnumSseMessageType;
import com.topnav.mc.sse.MessageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 其它通知消息通知处理
 * 包括固件升级，回放结事关流
 * @Author: kenny
 * @Date: 2023/11/11 18:24
 */
@Slf4j
@Component
public class OtherCommMessageListener implements MessageListener {
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private DeviceAlarmQueue deviceAlarmQueue;

    @Override
    public void onMessage(Message message, byte[] bytes) {

        CommMessage commMessage = JSON.parseObject(message.getBody(), CommMessage.class);

        if (commMessage.getMessageType() == ECommMessageType.UPGRADE_FINISH.getCode()){
            log.info(">>>>> 收到升级结果信息：code:{}, desc:{}",
                    commMessage.getDeviceId(),commMessage.getMessageDesc());
            if (commMessage.getBody() != null){
                JSONObject jsonObject = (JSONObject)commMessage.getBody();
                log.info(">>>>> {}",jsonObject.toString());

                String note = "";
                if ("OK".equals(jsonObject.get("upgradeResult").toString())){
                    note = DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss") + "固件升级成功";
                }else{
                    note = DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss") + "固件升级失败，失败原因："
                            + jsonObject.get("reasonDesc").toString();
                }
                deviceService.update(
                        new UpdateWrapper<Device>().set("note",note).eq("code",commMessage.getDeviceId())
                );

            }
        }else if (commMessage.getMessageType() == ECommMessageType.REPLAY_FINISH.getCode()){
            log.info(">>>>> 收到回放开流通知：code:{}, desc:{}",commMessage.getDeviceId(),commMessage.getMessageDesc());
            //回放结束
            //这处数据不多，不用队列了
            JSONObject json = new JSONObject();
            json.put("deviceCode",commMessage.getDeviceId());
            json.put("finished",true);
            MessageBean messageBean = new MessageBean(EnumSseMessageType.MEDIA_REPLAY_FINISHED);
            messageBean.setMessage(json);
            deviceAlarmQueue.offer(messageBean);
        }

    }
}
